package com.seelyn.ddvideo.spider;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seelyn.ddvideo.event.ParseErrorEvent;
import com.seelyn.ddvideo.event.SystemEventPublisher;
import com.seelyn.ddvideo.model.Video;
import com.seelyn.ddvideo.model.VideoPlayer;
import com.seelyn.ddvideo.service.VideoService;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author slacrey
 * @since 2017/6/10
 */
public class QQVideoPageProcessor implements PageProcessor {

    private VideoService videoService;
    private SystemEventPublisher eventPublisher;

    public QQVideoPageProcessor(SystemEventPublisher eventPublisher, VideoService videoService) {
        this.eventPublisher = eventPublisher;
        this.videoService = videoService;
    }

    private Site site = Site.me().setDomain("list.video.qq.com")
            .setCharset("UTF-8")
            .setSleepTime(100)
            .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    private Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        return formatter.parse(strDate, pos);
    }

    @Override
    public void process(Page page) {


        Video video = null;
        HashMap<String, Object> hashMap = new HashMap<>();
        JSONObject jsonObject = page.getJson().removePadding("jqcallback").toObject(JSONObject.class);

        JSONObject jsonValue = jsonObject.getJSONObject("jsonvalue");

        JSONArray jsonArray = jsonValue.getJSONArray("results");
        if (jsonArray == null || jsonArray.isEmpty()) {
            eventPublisher.publishParseError(new ParseErrorEvent(null, FromSiteEnum.QQ, MovieTypeEnum.all, PageTypeEnum.LIST));
            return;
        }

        JSONObject itemObj = null;
        JSONObject fieldsObj = null;
        JSONObject scoreObj = null;
        JSONObject tagObj = null;
        int count = jsonArray.size() - 1;
        for (int i = count; i >= 0; i--) {
            itemObj = jsonArray.getJSONObject(i);
            if (itemObj == null) {
                eventPublisher.publishParseError(new ParseErrorEvent(video, FromSiteEnum.QQ, MovieTypeEnum.all, PageTypeEnum.LIST));
                continue;
            }
            String id = itemObj.getString("id");
            fieldsObj = itemObj.getJSONObject("fields");
            scoreObj = fieldsObj.getJSONObject("score");
            Integer type = fieldsObj.getInteger("type");
            Date online_time = fieldsObj.getDate("online_time");
            String title = fieldsObj.getString("title");
            String vertical_pic_url = fieldsObj.getString("vertical_pic_url");
            Float score = scoreObj == null ? 0 : scoreObj.getFloat("score");

            video = new Video();
            video.setDelFlag(false);
            video.setTitle(title);
            video.setPicUrl(vertical_pic_url);
            video.setScore(score);
            video.setVid(id);
            video.setOnlineTime(new Date().getTime());

            Video oldVideo = videoService.findVideoByTitle(title);
            if (oldVideo != null) {
                video.setId(oldVideo.getId());
                video.setVideoFroms(oldVideo.getVideoFroms());
            }

            if (type.equals(1)) {
                // 电影
                video.setMovieType(MovieTypeEnum.movie.ordinal());

                List<VideoPlayer> players = video.getPlayers(FromSiteEnum.QQ);
                VideoPlayer videoPlayer = new VideoPlayer();
                videoPlayer.setOrder(1);
                videoPlayer.setUrl("https://v.qq.com/x/cover/" + id + ".html");
                videoPlayer.setName(title);

                //清空以前存在的播放地址
                players.clear();
                players.add(videoPlayer);

                videoService.saveVideo(video);

            } else if (type.equals(2)) {

                //电视剧
                String updateText = fieldsObj.getJSONObject("web20_imgtag").getJSONObject("tag_3").getString("text");
                video.setUpdateText(updateText);
                video.setMovieType(MovieTypeEnum.tv.ordinal());
                Spider.create(new QQVideoInfoTVProcessor(eventPublisher, videoService, video))
                        .addUrl("http://v.qq.com/detail/" + id.charAt(0) + "/" + id + ".html")
                        .run();

            } else if (type.equals(3)) {

                //动漫
                String updateText = fieldsObj.getJSONObject("web20_imgtag").getJSONObject("tag_3").getString("text");
                video.setUpdateText(updateText);
                video.setMovieType(MovieTypeEnum.cartoon.ordinal());
                Spider.create(new QQVideoInfoCartoonProcessor(eventPublisher, videoService, video))
                        .addUrl("http://v.qq.com/detail/" + id.charAt(0) + "/" + id + ".html")
                        .run();

            }

        }

    }

    @Override
    public Site getSite() {
        return site;
    }


}
